<script setup lang="ts">
import type { PropType } from 'vue'
import { computed, ref } from 'vue'
import { FilterFilled, SearchOutlined, SettingOutlined } from '@ant-design/icons-vue'
import type { TableOptions } from './types'
import CustomFilterDropdown from './CustomFilterDropdown.vue'

const props = defineProps({
  columns: {
    required: true,
    type: Array as PropType<TableOptions[]>,
  },
  data: {
    default() {
      return []
    },
    type: Array,
  },
})

const propColumns = computed(() => props.columns)

const actionColumn = computed(() => propColumns.value.find(column => column.dataIndex === 'action'))

const showTableColumns = ref<TableOptions[]>(propColumns.value)

const checkedOptions = computed({
  get() {
    return showTableColumns.value.map(column => column.dataIndex)
  },
  set(checked) {
    showTableColumns.value = propColumns.value.filter((column: TableOptions) => checked.includes(column.dataIndex))
  },
})
</script>

<template>
  <a-table
    :columns="showTableColumns"
    :data-source="props.data"
    v-bind="$attrs"
  >
    <template #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
      <CustomFilterDropdown
        :set-selected-keys="setSelectedKeys"
        :selected-keys="selectedKeys"
        :confirm="confirm"
        :clear-filters="clearFilters"
        :column="column"
      />
    </template>
    <template #customFilterIcon="{ filtered, column }">
      <SearchOutlined
        v-if="['dateTime', 'input'].includes(column.valueType)"
        :style="{ color: filtered ? '#108ee9' : undefined }"
      />
      <FilterFilled
        v-else
        :style="{ color: filtered ? '#108ee9' : undefined }"
      />
    </template>
    <template #headerCell="{ column }">
      <template v-if="column.dataIndex === 'action'">
        <div class="gp__flex-between">
          <span>{{ actionColumn?.title }}</span>
          <a-dropdown v-if="actionColumn?.actionIconPlace === 'inline'" :trigger="['click']">
            <SettingOutlined />
            <template #overlay>
              <a-menu>
                <a-checkbox-group v-model:value="checkedOptions" class="gp__flex-column">
                  <template v-for="option in propColumns" :key="option.id">
                    <a-checkbox :value="option.dataIndex" :disabled="option.disabled" style="padding: 4px 8px;">
                      {{ option.title }}
                    </a-checkbox>
                  </template>
                </a-checkbox-group>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </template>
    </template>
    <!-- 透传其他的 slot -->
    <template v-for="(_, key, index) in $slots" :key="index" #[key]="item">
      <slot :name="key" v-bind="item" />
    </template>
  </a-table>
</template>
